package yxy.game.pm2.command.friend;

import yxy.cherry.data.bean.friendsdate;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.FriendMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.friend.FriendHandle;
import yxy.game.pm2.module.friend.FriendModule;

import java.util.Collection;

/** 好友 领取友情点 */
@MessageType(proto = Command.FriendReceive, classtype = FriendMessage.FriendReceiveRequest.class)
public class CMD_FriendReceive extends Command<FriendMessage.FriendReceiveRequest> {

	@Override
	public void execute(MessageSource messageSource, FriendMessage.FriendReceiveRequest request) {
		String playerCode = messageSource.getTag();
		String friendCode = request.getPlayerCode();

		FriendMessage.FriendReceiveResponse.Builder response = FriendMessage.FriendReceiveResponse.newBuilder();

		FriendModule playerModule = FriendModule.get(playerCode);
		friendsdate data = playerModule.data();
		CurrencyHandle currencyHandle = new CurrencyHandle();
		try {
			if (playerModule.tryLock()) {
				if (!playerModule.getGiftn().contains(friendCode)) {
					// 赠送者没有这个好友
					send(messageSource, response, Result.FriendPointHasReceive);// 你已经领取过了
					return;
				}
				Collection<Currency> rewards = Currency.create(data.getReceivegettype(), data.getReceivegetid(), data.getReceivegetnum());
				currencyHandle.addCurrency(playerCode, CCReason.好友, rewards);

				playerModule.getGiftn().remove(friendCode);
				playerModule.set();

				FriendMessage.Friend friend = new FriendHandle().packFriend(playerModule, friendCode);
				response.setFriend(friend);
				response.addAllReceive(currencyHandle.packItems(rewards));
				send(messageSource, response, Result.Success);

			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			playerModule.unlock();
		}
	}

	private void send(MessageSource messageSource, FriendMessage.FriendReceiveResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}